import Config from './config.js'
import store from "../store/index.js"
function request(url, options) {
	var method = options.method || 'GET';
	// console.log(TOKEN)
	var data = {}
	const token = uni.getStorageSync('token');
	data = options.data;
	// console.log(data)
	// #ifndef H5
	    let baseUrl = Config.http + Config.hostName
	// #endif
	// #ifdef H5
	     let baseUrl = ''
	// #endif
	// 0：无异常  50000 是通用异常  50001要重新登录
	function logout(res) {
		if(res.data.code == '50001') {
			uni.setStorageSync('token', '');
			uni.showToast({
				title: res.data.msg,
				icon: 'none',
				duration: 2000
			})
			// setTimeout(()=>{
			// 	uni.reLaunch({
			// 		url:'/pages/login/login'
			// 	})
			// },1000)
			return
		}
	}
    // uni.showLoading({title: '加载中'})
	return new Promise((resolve, rej) => {
		uni.request({
			url: baseUrl + url,
			method: method,
			data: data,
			header: {
				'content-type': 'application/json',
				'X-Requested-With': 'XMLHttpRequest',
				'token': token
			},
			success: res => {
				var msg = ''
				if (res.statusCode == 500) {
					// logout(res)
				}
				if (res.statusCode.toString().charAt(0) == '2') {
					
					if(res.data.code == '50000') {
						uni.showToast({
							title: res.data.msg,
							icon: 'none',
							duration: 2000
						})
					}
					if(res.data.code == '50001') {
						// logout(res)
					}
					
				}

		
				// uni.hideLoading()
				resolve(res.data)
			},
			fail: res => {
				console.log(res)
				uni.showModal({
					showCancel: false,
					title: '提示',
					content: '网络环境异常,请检查网络后重试'
				})
				// uni.hideLoading()
				return rej(res)
			},
			complete: res => {
				// uni.hideLoading()
			}
		});
	})
}


export function post(url, data = {}) {
	return request(url, {
		method: 'POST',
		data
	})
}

export function get(url, data = {}) {
	return request(url, {
		method: 'GET',
		data
	})
}

export function put(url, data = {}) {
	return request(url, {
		method: 'PUT',
		data
	})
}
export function _delete(url, data = {}) {
	return request(url, {
		method: 'DELETE',
		data
	})
}
